<template>
  <div class="page-controller">
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      v-model:form-value="state.query"
      :exclude-values="[ 'groupCname', 'groupCname1', 'nodeName']"
      :table-column="columns"
      :wrapperSpan="searchWrapperSpan"
      @submit="searchFn"
      @reset="resetFn"
    >
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="productNo" label="产品号">
          <FIInput v-model="state.query.productNo" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="productName" label="产品名称">
          <FIAutoSelect
            v-model="state.query.productName"
            :props="{ value: 'productName', label: 'productName' }"
            :display-key="['productNo', 'productName']"
            api-url="/bpm-service/ProcEffi/queryProduct"
            searchParam="productNo"
          />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="prodPeriodName" label="分期名称">
          <FIInput v-model="state.query.prodPeriodName" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="manager" label="信托经理">
          <FIAutoInput
            v-model="state.query.manager"
            :options="userList"
            value-key="userCName"
            :displayKey="['loginName', 'userCName']"
            @select="selectClick($event, 'manager')"
            @change="changeEvent($event, 'manager')"
          >
            <template #default="{ item }">
              <div>{{ item.loginName }} {{ item.userCName }}</div>
            </template>
          </FIAutoInput>
          <!-- <FIAutoSelect
            v-model="state.query.manager"
            :props="{ value: 'loginName', label: 'userCName' }"
            :display-key="['loginName','userCName']"
            api-url="/rm2/userMaint/query"
            searchParam="userAName"
          /> -->
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="processKey" label="流程名称">
          <ProcessName v-model="state.query.processKey"></ProcessName>
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="startId" label="流程发起人">
          <FIAutoInput
            v-model="state.query.startId"
            :options="userList"
            value-key="userCName"
            :displayKey="['loginName', 'userCName']"
            @select="selectClick($event, 'fqr')"
            @change="changeEvent($event, 'fqr')"
          >
            <template #default="{ item }">
              <div>{{ item.loginName }} {{ item.userCName }}</div>
            </template>
          </FIAutoInput>
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="startDeptId" label="发起部门">
          <DeptTree v-model="state.query.startDeptId" />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="taskKey" label="任务节点">
          <TaskName v-model="state.query.taskKey" />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="taskDept" label="任务部门">
          <DeptTree v-model="state.query.taskDept" />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="operator" label="操作人">
          <FIAutoInput
            v-model="state.query.operator"
            :options="userList"
            value-key="userCName"
            :displayKey="['loginName', 'userCName']"
            @select="selectClick($event, 'czr')"
            @change="changeEvent($event, 'czr')"
          >
            <template #default="{ item }">
              <div>{{ item.loginName }} {{ item.userCName }}</div>
            </template>
          </FIAutoInput>
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="vote" label="表决">
          <!-- <FIAutocomplete :dataArr="voteOpt" valueKey="vote" queryKey="vote" value-key="vote" :valueKeyArr="['vote']" v-model="state.query.vote">
            <template #default="{ item }">
              <div v-if="item && item.vote">{{ item.vote }}</div>
              <div v-else>{{ item }}</div>
            </template>
          </FIAutocomplete> -->
          <FIAutocomplete
            v-model="state.query.vote"
            valueKey="vote"
            :dataArr="voteOpt"
          >
            <template #default="{ item }">
              <div v-if="item && item.vote">{{ item.vote }}</div>
              <div v-else>{{ item }}</div>
            </template>
          </FIAutocomplete>
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="sequenceId" label="流程实例">
          <FIInput v-model="state.query.sequenceId" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem class="date-range-class" prop="startTimeStart" label="开始时间">
          <FIDatePicker
            value-format="YYYYMMDD"
            v-model="state.query.startTimeStart"
            type="date"
            placeholder="时间"
            clearable
          />
          <FIDatePicker
            value-format="YYYYMMDD"
            v-model="state.query.startTimeEnd"
            type="date"
            placeholder="时间"
            clearable
          />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem class="date-range-class" prop="endTimeStart" label="结束时间">
          <FIDatePicker
            value-format="YYYYMMDD"
            v-model="state.query.endTimeStart"
            type="date"
            placeholder="时间"
            clearable
          />
          <FIDatePicker
            value-format="YYYYMMDD"
            v-model="state.query.endTimeEnd"
            type="date"
            placeholder="时间"
            clearable
          />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem class="date-range-class" prop="processStartTimeStart" label="流程发起时间">
          <FIDatePicker
            value-format="YYYYMMDD"
            v-model="state.query.processStartTimeStart"
            type="date"
            placeholder="时间"
            clearable
          />
          <FIDatePicker
            value-format="YYYYMMDD"
            v-model="state.query.processStartTimeEnd"
            type="date"
            placeholder="时间"
            clearable
          />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="instStatus" label="流程状态">
          <FISelect v-model="state.query.instStatus" valueCustom="value" :options="processStatus" clearable />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <div class="margin-bottom20"></div>
    <FITable
      ref="tableRef"
      class="box-radius2"
      title="流程效率跟踪明细记录集"
      :id="`result_${tableId}`"
      :readonly="false"
      :data="state.dataList"
      primaryKey="id"
      :rowNo="true"
      v-model:columns="columns"
      :insertable="false"
      :showSaveModel="false"
      :isLoading="isTableLoading"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @action-click="actionClick"
    >
      <template #headerBtn>
        <FIButton id="export" border @click="exportClick"></FIButton>
      </template>
    </FITable>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIButton from '@/components/FIButton.vue'
import FIAutocomplete from '@/components/FIAutocomplete.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import ProcessName from '../../components/ProcessName.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import DeptTree from '../../components/DeptTree'
import TaskName from '../../components/TaskName'
import { apiRequestPost } from '@/api/globalApi.js'
import { ElMessage } from 'element-plus'
import { useMessage, useMessageBox } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import {
  apiQueryVote,
  apiQueryDetails,
  apiExportDetails,
  apiQueryUser,
  apiQueryDept,
  apiQueryProcessesDef,
  apiQueryProduct,
  apiQueryProcessNode,
} from '@/api/modules/EW.js'
const route = useRoute()
const productPage = ref(1)
const loadMoreEnd = ref(false)
const searchWrapperSpan = 8
const processArr = ref([])
const isTableLoading = ref(false)
const processPage = ref(1)
// 页面编码
const tableId = 'usersAudit'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const tableRef = ref(null)
const userList = ref([])
const deptList = ref([])
const productList = ref([])
const processNodeArr = ref([])
const nodeCurrent = ref(1)
const voteOpt = ref([])
const state = reactive({
  query: {
    taskKey: '',
    productNo: '',
    productName: '',
    processKey: '',
    manager: '',
    startTimeStart: '',
    startTimeEnd: '',
    endTimeStart: '',
    endTimeEnd: '',
    startDeptId: '',
    taskDept: '',
    sequenceId: '',
    prodPeriodName: '',
    operator: '',
    startId: '',
    instStatus: '',
    vote: '',
    processStartTimeStart: '',
    processStartTimeEnd: '',
    current: 1,
    size: 10,
    // userCName: '',
    groupCname: '',
    groupCname1: '',
  },
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})
const processStatus = [
  {
    value: 'active',
    label: '正运行',
  },
  {
    value: 'suspend',
    label: '挂起',
  },
  {
    value: 'finish',
    label: '结束',
  },
  {
    value: 'manual-finish',
    label: '终止',
  },
]
const columns: Column[] = reactive([
  {
    label: '产品号',
    prop: 'productNo',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '产品名称',
    prop: 'productName',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '信托经理',
    prop: 'manager',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '分期名称',
    prop: 'prodPeriodName',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '流程实例',
    prop: 'sequenceId',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '流程名称',
    prop: 'processName',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '发起人',
    prop: 'startId',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '发起部门',
    prop: 'startDeptId',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '任务节点',
    prop: 'taskNode',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '任务部门',
    prop: 'taskDept',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '操作人',
    prop: 'operator',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '开始时间',
    prop: 'startTime',
    align: 'center',
    editType: 'date-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '结束时间',
    prop: 'endTime',
    align: 'center',
    editType: 'date-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '表决',
    prop: 'vote',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '备注',
    prop: 'remark',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },

  // {
  //   label: '',
  //   prop: 'action',
  //   actionConfig: [{ id: 'isTop', type: 'top' }],
  // },
])

const checkedRows = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
const resetFn = () => {
  state.query.groupCname = ''
  // state.query.userCName = ''
  state.query.productName = ''
  state.query.manager = ''
  state.query.nodeName = ''
  state.query.groupCname1 = ''
  // state.query.userCName1 = ''
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
const changeEvent = (e, type) => {
  if (!e) {
    if (type == 'fq_dept') state.query.startDeptId = ''
    if (type == 'fqr') state.query.startId = ''
  }
}
const selectClick = (data, type) => {
  console.log(data, type, 'data123')
  if (type == 'fqr') {
    state.query.startId = data.loginName
  } else if (type == 'fq_dept') {
    state.query.startDeptId = data.groupEname
  } else if (type == 'product') {
    state.query.productNo = data.productNo
  } else if (type == 'manager') {
    state.query.manager = data.loginName
  } else if (type == 'rwjd') {
    state.query.taskKey = data.nodeKey
  } else if (type == 'czr') {
    state.query.operator = data.loginName
  } else if (type == 'process') {
  }
}
//导出
const exportClick = () => {
  apiExportDetails(state.query)
}

//操作
const actionClick = (item, rowData, btnInfo) => {
  console.log(rowData, 'rowData')
  // useMessageBox()
  //   .confirm(`您确认要置顶吗？`, '提示')
  //   .then(() => {
  //     apiExchangeSortIndex([rowData.id,0])
  //         .then((res) => {
  //           console.log(res, 'res123')
  //           if (res.data.success) {
  //             useMessage().success(res.data.message)
  //             searchFn()
  //           } else {
  //           }
  //         })
  //         .catch((error: any) => {})
  //   })
  //   .catch(() => {})
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}

const searchFn = (type?: string, columnsVal?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns

  if (type == 'page') {
    state.query.current = pageConfig.currentPage
  } else {
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize

  let par = {
    ...state.query,
    // startTime: state.query.startTimeStart ? state.query.startTimeStart[0] : '',
    // endTime: state.query.startTimeStart ? state.query.startTimeStart[1] : '',
  }
  // delete par.startTimeStart
  apiQueryDetails(par)
    .then((res) => {
      console.log(res, 'res')
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        // console.log(state.dataList)
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  apiRequestPost('/rm2/pageMaint/save', checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        tableRef.value.clearSelection()
        searchFn()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const getBJlist = () => {
  apiQueryVote({ vote: '' })
    .then((res) => {
      if (res.data.success) {
        // let obj = {}
        for(let i of res.data.data){
          if(i){
            voteOpt.value.push(i)
          }
        }
        // voteOpt.value = res.data.data
        console.log(voteOpt.value, 'voteOpt')
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {})
}
const ruleFormRef = ref(null)

const addRowSave = (data) => {
  handleSave()
}
const processloadMore = () => {
  if (loadMoreEnd.value && processPage.value > 1) return
  processPage.value++
  getQueryAll()
}
const productloadMore = () => {
  if (loadMoreEnd.value && productPage.value > 1) return
  productPage.value++
  getProductList()
}
const getProductList = () => {
  let par = {
    current: productPage.value,
    size: 10,
  }
  apiQueryProduct(par)
    .then((res) => {
      console.log(res, 'res123456')
      if (res.data.success) {
        // productList.value = res.data.data.result
        productList.value = productList.value.concat(res.data.data.result)
        if (productPage.value * 10 >= res.data.data.count) {
          loadMoreEnd.value = true
        }
      }
    })
    .catch((error: any) => {})
}
const getQueryUser = () => {
  apiQueryUser()
    .then((res) => {
      console.log(res, 'res123456')
      if (res.data.success) {
        userList.value = res.data.data
      } else {
      }
    })
    .catch((error: any) => {})
}
const getQueryDept = () => {
  apiQueryDept()
    .then((res) => {
      console.log(res, 'res123456')
      if (res.data.success) {
        deptList.value = res.data.data
      } else {
      }
    })
    .catch((error: any) => {})
}
const getQueryAll = () => {
  let par = {
    current: processPage.value,
    size: 10,
  }
  apiQueryProcessesDef(par)
    .then((res) => {
      if (res.data.success) {
        processArr.value = processArr.value.concat(res.data.data.result)
        if (processPage.value * 10 >= res.data.data.count) {
          loadMoreEnd.value = true
        }
      }
    })
    .catch((error: any) => {})
}
const nodeloadMore = () => {
  if (loadMoreEnd.value && nodeCurrent.value > 1) return
  nodeCurrent.value++
  getTaskNode()
}
const getTaskNode = () => {
  let par = {
    current: nodeCurrent.value,
    size: 10,
  }
  apiQueryProcessNode(par)
    .then((res) => {
      if (res.data.success) {
        processNodeArr.value = processNodeArr.value.concat(res.data.data.result)
        if (processPage.value * 10 >= res.data.data.count) {
          loadMoreEnd.value = true
        }
      }
    })
    .catch((error: any) => {})
}
onMounted(() => {
  getQueryUser() //查询人员
  getQueryDept() //查询部门
  getBJlist() //获取表决数据
  getQueryAll() //查询流程名称
  getProductList() //获取产品列表
  getTaskNode() //获取任务节点
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  // searchFn()//初始化不掉数据
})
</script>
<style lang="less" scoped>
.date-range-class {
  display: flex !important;
  ::v-deep(.el-form-item__content) {
    width: 220px !important;
    display: flex !important;
    justify-content: space-between !important;
    .el-input__prefix {
      display: none !important;
    }
    .el-input {
      width: 107px !important;
    }
  }
}
</style>
